package com.eet.elasticsearch.utils;

import com.eet.elasticsearch.entity.JdContentDto;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 解析HTML
 *
 * @author zheng.zhang
 */
public class HtmlParseUtil {

    /**
     * 爬取京东浏览页数据
     *
     * @throws IOException IO异常
     */
    public static List<JdContentDto> parseJd(String keywords) throws IOException {
        ArrayList<JdContentDto> list = new ArrayList<>();
        if (StringUtils.isEmpty(keywords)) {
            return list;
        }
        String url = "https://search.jd.com/Search?keyword=".concat(keywords);
        // 解析网页,浏览器Document对象
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");

        // 获取所有的li标签
        Elements liElements = element.getElementsByTag("li");
        // 获取元素中的内容
        for (Element el : liElements) {
            String imgSrc = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();

            list.add(JdContentDto.builder()
                    .title(title)
                    .price(price)
                    .imgSrc(imgSrc)
                    .build());
        }
        return list;
    }
}
